package com.example.baselibrary.services

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.speech.tts.TextToSpeech
import android.speech.tts.TextToSpeech.OnInitListener
import android.util.Log
import com.example.baselibrary.enums.LanguageType
import com.example.baselibrary.enums.SpeakActionType
import com.example.baselibrary.eventbus.EventSpeakActionBus
import com.example.baselibrary.eventbus.EventStringBus
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

class TextToSpeechService : Service(), OnInitListener {
    private var tts: TextToSpeech? = null
    private var isInitialized = false

    override fun onCreate() {
        super.onCreate()
        initializeTTS()
        EventBus.getDefault().register(this)
    }

    private fun initializeTTS() {
        tts = TextToSpeech(this, this)
    }

    override fun onInit(status: Int) {
        when (status) {
            TextToSpeech.SUCCESS -> {
                isInitialized = true
                Log.d(TAG, "TextToSpeech initialized successfully")
            }
            else -> {
                isInitialized = false
                Log.e(TAG, "Failed to initialize TextToSpeech, status: $status")
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: EventStringBus) {
        when (event.language) {
            LanguageType.CHINESE -> {
                speak(event.str, Locale.CHINA)
            }
            LanguageType.ENGLISH -> {
                speak(event.str, Locale.US)
            }
            LanguageType.KOREAN -> {
                speak(event.str, Locale.KOREA)
            }
            LanguageType.JAPANESE -> {
                speak(event.str, Locale.JAPAN)
            }
            else -> {
                speak(event.str)
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onActionEvent(event: EventSpeakActionBus) {
        if (event.action == SpeakActionType.isSpeaking){

        }else if (event.action == SpeakActionType.stopSpeak){
            stop()
        }
    }


    /**
     * 播放文本，自动适配语言
     */
    fun speak(text: String, locale: Locale = Locale.getDefault(), utteranceId: String? = null) {
        if (!isInitialized) {
            Log.w(TAG, "TTS not initialized, cannot speak")
            return
        }

        if (text.isBlank()) {
            Log.w(TAG, "Empty text provided to speak")
            return
        }

        try {
            // 设置语言
            val result = tts?.setLanguage(locale)
            when (result) {
                TextToSpeech.LANG_MISSING_DATA -> {
                    Log.e(TAG, "Language data is missing for locale: $locale")
                    return
                }
                TextToSpeech.LANG_NOT_SUPPORTED -> {
                    Log.e(TAG, "Language is not supported: $locale")
                    return
                }
            }

            // 构造参数
            val params = android.os.Bundle().apply {
                utteranceId?.let { putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, it) }
            }

            // 播放文本
            val speakResult = tts?.speak(
                text,
                TextToSpeech.QUEUE_FLUSH,
                params,
                utteranceId ?: UUID.randomUUID().toString()
            ) ?: TextToSpeech.ERROR

            if (speakResult == TextToSpeech.ERROR) {
                Log.e(TAG, "Error speaking text: $text")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Exception while speaking text: $text", e)
        }
    }

    /**
     * 添加文本到播放队列，自动适配语言
     */
    fun addToSpeakQueue(text: String, locale: Locale = Locale.getDefault(), utteranceId: String? = null) {
        if (!isInitialized) {
            Log.w(TAG, "TTS not initialized, cannot queue speech")
            return
        }

        if (text.isBlank()) {
            Log.w(TAG, "Empty text provided to queue")
            return
        }

        try {
            // 设置语言
            val result = tts?.setLanguage(locale)
            when (result) {
                TextToSpeech.LANG_MISSING_DATA -> {
                    Log.e(TAG, "Language data is missing for locale: $locale")
                    return
                }
                TextToSpeech.LANG_NOT_SUPPORTED -> {
                    Log.e(TAG, "Language is not supported: $locale")
                    return
                }
            }

            // 构造参数
            val params = android.os.Bundle().apply {
                utteranceId?.let { putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, it) }
            }

            // 添加到播放队列
            val queueResult = tts?.speak(
                text,
                TextToSpeech.QUEUE_ADD,
                params,
                utteranceId ?: UUID.randomUUID().toString()
            ) ?: TextToSpeech.ERROR

            if (queueResult == TextToSpeech.ERROR) {
                Log.e(TAG, "Error adding text to queue: $text")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Exception while queuing text: $text", e)
        }
    }

    /**
     * 停止当前播放
     */
    fun stop() {
        tts?.stop()
    }

    /**
     * 检查是否正在播放
     */
    fun isSpeaking(): Boolean = tts?.isSpeaking ?: false

    override fun onBind(intent: Intent): IBinder? = null

    override fun onDestroy() {
        tts?.apply {
            stop()
            shutdown()
        }
        tts = null
        isInitialized = false
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    companion object {
        private const val TAG = "TextToSpeechService"
    }
}
